from urllib import request, parse
from datetime import datetime, timedelta
from pymongo import MongoClient, ASCENDING, DESCENDING

import configparser
import time
import json

class Zabbix_api(object):
    def __init__(self):
        self.config_file = r"conf\config.ini"
        self.config = configparser.ConfigParser()
        self.config.read(self.config_file, encoding='utf-8')
        self.url = self.config.get('zabbix','url')
        self.username = self.config.get('zabbix','username')
        self.password = self.config.get('zabbix','password')
        self.token = self.config.get('zabbix','token')
        self.values = {
            "jsonrpc": "2.0",
            "id": "0"
        }
        self.config.clear()

    def Get_Datetime(self):
        """
        mstartdate：上个月开始时间
        enddate：年和月的结束时间
        wmstartdate:当月第一天
        days：今天
        wstartdate：上周开始时间
        wenddate：上周结束时间
        """
        today = datetime.today()
        year = today.year
        month = today.month
        days = today.strftime('%Y-%m-%d') + " 00:00:00"
        week = today.isoweekday()

        mstartdate = datetime(year, month - 1, 1)
        wmstartdate = datetime(year, month , 1)
        ystartdate = datetime(year - 1, month, 1)
        enddate = datetime(year, month, 1, 23, 59, 59) + timedelta(days=-1)
        wstartdate = datetime.strptime(days, '%Y-%m-%d %H:%M:%S') + timedelta(days=-(week + 6))
        wenddate = datetime.strptime(days, '%Y-%m-%d %H:%M:%S') + timedelta(days=-(week-1))
        all_date_time = [(int(time.mktime(wstartdate.timetuple())),int(time.mktime(wenddate.timetuple()))), (int(time.mktime(wmstartdate.timetuple())), int(time.mktime(datetime.strptime(days, '%Y-%m-%d %H:%M:%S').timetuple()))), (int(time.mktime(mstartdate.timetuple())),int(time.mktime(enddate.timetuple())))]
        return all_date_time

    def mongodb_api_con(self):
        try:
            # 认证（密码无特殊符号）
            self.config.read(self.config_file)
            mac_host = self.config.get('mongodb', 'host')
            mac_port = self.config.get('mongodb', 'port')
            mac_dbname = self.config.get('mongodb', 'dbname')
            mac_user = self.config.get('mongodb', 'username')
            mac_pwd = self.config.get('mongodb', 'passwd')
            # mongo_client = MongoClient('mongodb://'+user+':'+pwd+'@'+host+':'+port+'/'+dbname+'?')
            # 认证（密码含特殊符号）
            mac_mongo_client = MongoClient(mac_host)
            mac_mongo_client[mac_dbname].authenticate(mac_user, mac_pwd, mac_dbname)
            # 连接到库：kafkadb
            mac_newdb = mac_mongo_client.api
            self.config.clear()
            return mac_newdb
        except:
            print('alarmserver mongodb数据库连接不上')

    def request_data(self, rd_values):
        """
        请求数据接口
        """
        rd_data = json.dumps(rd_values)
        rd_req = request.Request(self.url, rd_data, {"Content-Type": "application/json-rpc"})
        rd_b_data = bytes(rd_data, encoding="utf8")
        rd_response = request.urlopen(rd_req, rd_b_data)
        rd_output = json.loads(rd_response.read())
        return rd_output


    def Auth_logout(self):
        """
        token在没有logout的情况下都是有效的
        """
        ao_values = self.values
        ao_values["method"] = "user.logout"
        ao_values["params"] = []
        ao_values["id"] = 0
        ao_values["auth"] = "e13ac835b7ddbb9b7aa0e76d05bc28f3"
        self.request_data(ao_values)

    def Auth_login(self):
        """
        获取token
        """
        ai_values = self.values
        ai_values["method"] = "user.login"
        ai_values["params"] = {
            "user": self.username,
            "password": self.password
        }
        self.request_data(ai_values)

    def Host_ID(self):
        hi_values = self.values
        zid = {}
        zip = {}
        hi_values["method"] = "host.get"
        hi_values["params"] = {
            "output": [
                "hostid",
                "host",
                "available",
                "error",
                "errors_from"
            ],
            "selectInterfaces": [
                "interfaceid",
                "ip"
            ]
        }
        hi_values["auth"] = self.token
        hi_output = self.request_data(self.values)
        hi_out_result = hi_output["result"]
        for i in hi_out_result:
            zid[i["host"]] = i["hostid"]
            zip[i["host"]] = i["interfaces"][0]["ip"]
        return zid, zip

    def trigger_data(self):
        """
        当前触发事件 
        """
        # td_datetime = self.Get_Datetime()
        # print(td_datetime[0][0])
        # td_time_c = int(time.mktime(td_datetime[0][0].timetuple()))
        td_values = self.values
        td_values["method"] = "trigger.get"
        td_values["params"] = {
            # "hostids": td_v,
            "expandDescription": True,
            "expandData": True,
            "expandComment": True,
            "monitored": True,
            "skipDependent": True,
            # "lastChangeSince": 1508919270,
            "output":[
                "triggerid",
                "description",
                "status",
                "value",
                "priority",
                "state",
                "lastchange",
            ],
            "filter": {
                "value":[0, 1]
            },
            # "selectGroups": [
            #     "name"
            # ],
            "selectHosts": [
                "name",
                "host",
            ],
            # "selectItems": [
            #     "name",
            #     "key_",
            #     "lastvalue"
            # ],
            # "selectLastEvent": "extend",
            "sortfield": "lastchange",
            "sortorder": "DESC"
        }
        td_values["auth"] = self.token
        td_output = self.request_data(td_values)
        try:
            td_results = td_output["result"]
        except:
            print(td_output["error"])
            td_results = 0
        finally:
            return td_results

    def Deal_trigger_data(self):
        dtd_data = self.trigger_data()
        dtd_mog_con = self.mongodb_api_con()
        dtd_date = datetime.now()
        if dtd_data == 0:
            pass
        else:
            trigger_mog_len = dtd_mog_con.zabbix_trigger.find({}).count()
            trigger_api_len = len(dtd_data)
            print('数据库数据量：%s，当前数据量：%s' % (trigger_mog_len, trigger_api_len))

            #第一次加载所有数据
            # for dtd_i in dtd_data:
            #     dtd_i["time"] = dtd_date
            #     dtd_i["lastchange"] = int(dtd_i["lastchange"])
            #     dtd_i["hostid"] = dtd_i["hosts"][0]["hostid"]
            #     dtd_i["name"] = dtd_i["hosts"][0]["name"]
            #     dtd_i["hosts"] = dtd_i["hosts"][0]["host"]
            #     dtd_mog_con.zabbix_trigger.insert_one(dtd_i)

            dtd_last_times = dtd_mog_con.zabbix_trigger.find({}).sort('lastchange', DESCENDING).limit(1)[0]["lastchange"]
            if trigger_mog_len < trigger_api_len:
                dtd_last = dtd_mog_con.zabbix_trigger.find({}).sort('triggerid', DESCENDING).limit(1)[0]

                for dtd_i in dtd_data:
                    if int(dtd_i["lastchange"]) > dtd_last_times:
                        dtd_result = dtd_mog_con.zabbix_trigger.find_one({'triggerid':dtd_i["triggerid"]})
                        if dtd_result:
                            dtd_mog_con.zabbix_trigger.update_one({'triggerid':dtd_i["triggerid"]},{'$set':{'description':dtd_i["description"], 'value': dtd_i["value"], 'lastchange':int(dtd_i["lastchange"]), 'priority':dtd_i["dtd_i"], 'time':dtd_date}})
                            print("更新  %s  状态" % dtd_i["description"])
                        else:
                            if dtd_i["triggerid"] > dtd_last["triggerid"]:
                                dtd_i["time"] = dtd_date
                                dtd_i["lastchange"] = int(dtd_i["lastchange"])
                                dtd_i["hostid"] = dtd_i["hosts"][0]["hostid"]
                                dtd_i["name"] = dtd_i["hosts"][0]["name"]
                                dtd_i["hosts"] = dtd_i["hosts"][0]["host"]
                                dtd_mog_con.zabbix_trigger.insert_one(dtd_i)
                                print("添加  %s  状态" % dtd_i["description"])
            else:
                for dtd_i in dtd_data:
                    if int(dtd_i["lastchange"]) > dtd_last_times:
                        dtd_mog_con.zabbix_trigger.update_one({'triggerid': dtd_i["triggerid"]}, {'$set': {'description': dtd_i["description"], 'value': dtd_i["value"],'lastchange': int(dtd_i["lastchange"]), 'time': dtd_date}})
                        print("更新  %s  状态" % dtd_i["description"])


    def return_trigger_data(self):
        """
         rtd_date_list:
         0:当天发生的问题数量
        """
        rtd_mog_con = self.mongodb_api_con()
        rtd_datetime = self.Get_Datetime()
        rtd_date = datetime.now().strftime('%Y-%m-%d')
        rtd_date_count = rtd_mog_con.zabbix_trigger.find({'lastchange':{'$gte':rtd_datetime[1][1]},}).count()
        rtd_mog_con.zabbix_count.update_one({"date": rtd_date}, {'$set': {'count': rtd_date_count}}, upsert=True)
        return rtd_date_count

    def return_api(self):
        while True:
            self.Deal_trigger_data()
            # ra_trigger_count = self.return_trigger_data()
            # print(ra_trigger_count)
            time.sleep(60)


    #[{'name': 'zabbix server', 'problem': '端口侦听异常', 'time': '2017-10-30 14:40', 'status': '故障'}];
    def select_data(self):
        sd_top_data = []
        sd_mog_con = self.mongodb_api_con()
        for sd_x in sd_mog_con.zabbix_trigger.find({}).sort('lastchange', DESCENDING).limit(20):
            sd_json = {}
            sd_json["name"] = sd_x["hosts"]
            sd_json["problem"] = sd_x["description"]
            sd_json["time"] = self.time_stamp(sd_x["lastchange"])
            sd_json["status"] = int(sd_x["value"])
            # sd_json["priority"] = sd_x["priority"]
            sd_top_data.append(sd_json)
        print(sd_top_data)
        return sd_top_data


    def time_stamp(self,ts_time):
        time_local = time.localtime(ts_time)
        td_dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        return td_dt



    # def trigger_data(self):
    #     """
    #     当前触发事件
    #     """
    #     # td_datetime = self.Get_Datetime()
    #     # print(td_datetime[0][0])
    #     # td_time_c = int(time.mktime(td_datetime[0][0].timetuple()))
    #     td_values = self.values
    #     td_zid, td_zip = self.Host_ID()
    #     td_trigger_all = []
    #     for td_k, td_v in td_zid.items():
    #         td_triggers = {}
    #         td_values["method"] = "trigger.get"
    #         td_values["params"] = {
    #             "hostids": td_v,
    #             "only_true": 0,
    #             "min_severity": 2,
    #             "monitored": 0,
    #             # "lastChangeTill": td_time_c,
    #             "output": [
    #                 "triggerid",
    #                 "description",
    #                 "priority"
    #             ],
    #             "filter": {
    #                 "value": 1
    #             },
    #             # "output" : "extend",
    #             "sortfield": "priority",
    #             "sortorder": "DESC"
    #         }
    #         td_output = self.request_data(td_values)
    #         td_results = td_output["result"]
    #         if len(td_results) != 0:
    #             td_triggers["servername"] = td_k
    #             td_triggers["ip"] = td_zip[td_k]
    #             td_triggers["error"] = td_results
    #             td_trigger_all.append(td_triggers)
    #     print(td_trigger_all)
    #     return td_trigger_all

    # def History_event(self):
    #     """
    #     历史事件确认信息
    #     """
    #     he_values = self.values
    #     he_values["method"] = "event.get"
    #     he_values["params"] = {
    #         "eventids":3,
    #         "output": "extend",
    #         "acknowledged": False,
    #         "select_acknowledges": "extend",
    #         "selectTags": "extend",
    #         "sortfield": ["clock", "eventid"]
    #     }
    #     he_values["auth"] = self.token
    #     ha_output = self.request_data(he_values)
    #
    # def History_problem(self):
    #     hp_datetime = self.Get_Datetime()
    #     print(hp_datetime[0][0])
    #     td_time_c = int(time.mktime(hp_datetime[0][0].timetuple()))
    #     hp_values = self.values
    #     hp_values["method"] = "problem.get"
    #     hp_values["params"] = {
    #         "hostids":10084,
    #         "output": "extend",
    #         "selectAcknowledges": "extend",
    #         "selectTags": "extend",
    #         "time_from": td_time_c
    #     }
    #     hp_values["auth"] = self.token
    #     self.request_data(hp_values)
